import React, { Component } from 'react';
import { Avatar, Badge, Icon, message, Modal } from 'antd'
import { withRouter } from 'react-router-dom'

import memory from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'
import { logout } from '../../api/index'
import './index.less'

const { confirm } = Modal
class Header extends Component {
    state = {
        collapsed: true
    }
    toggleCollaps = () => {
        let { collapsed } = this.state
        this.setState({
            collapsed: !collapsed
        })
        this.props.toggleCollapsed(this.state.collapsed)
    }
    logout = () => {
        confirm({
            title: '消息',
            content: '您确认要退出系统吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 调运退出接口
                const res = await logout()
                if (res.code === 0) { //如果成功
                    // 1、清除内心中的数据
                    memory.user = {}
                    // 2、清除浏览器存储的数据
                    storageUtils.remove('user')
                    // 3、调整到登录页面
                    this.props.history.replace('/login')
                    // 4、提示消息
                    message.success('退出成功')
                } else { // 如果失败
                    message.warn('退出失败')
                }
            }
        })
    }
    render () {
        let { collapsed } = this.state
        return (
            <div className='header'>
                <div className='header-left' onClick={this.toggleCollaps}>
                    <Icon type={collapsed ? 'menu-unfold' : 'menu-fold'} />
                </div>
                <div className="header-right">
                    <Badge count={25} offset={[2, -6]}>
                        <Icon type="bell" style={{ fontSize: '1rem' }} />
                    </Badge>
                    <Avatar icon="user" size="small" />
                    <span>{memory.user.username}</span>
                    <Icon type="logout" onClick={this.logout} style={{ fontSize: '1rem' }} />
                </div>
            </div>
        );
    }
}


export default withRouter(Header);